
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include "memory.h"
#include "end_memory.h"

extern int info[MAX_L];
extern int sum;
extern Buddy* p_tree;
extern void* base;
extern sem_t g_sem;

// end_memory() fuction implementation
void
end_memory(void)
{
    Buddy *tree = p_tree;
    int l, i, info_dif;
    int one = 1;
    int level_head, level_end;
    l = 0;
    info_dif = 0;
sem_wait(&g_sem);
    while ((info_dif = (one<<l) - info[l]) > 0) { // while there is mallocated block at this level
    
        level_head = (one<<l) - 1;      // to find the offset of the first node on this level.
        level_end = (one<<(l+1)) - 2;   // to find the offset of the last node on this level.

        for (i = level_head; info_dif > 0 && i <= level_end; i++) {
            if (tree[i].p != NULL && tree[i].left == NULL && tree[i].right == NULL) {
                mem_header_t *pointer = (mem_header_t *) tree[i].p;
                
                printf("Memory leak block %p, size %d\n",(void *)&pointer[1], pointer->size);
				info_dif --;
            }
        }

        l++;
    }

sem_post(&g_sem);
    free(p_tree);
	p_tree = NULL;
}


